/**
 * 
 */
package com.cap.bts.framework.sms.util;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;

import com.cap.bts.commonfunc.sms.dto.SmsStatus;
import com.cap.bts.crmdp.dealer.mars.dto.MARSParamDto;
import com.cap.bts.framework.sms.constant.HttpSMSConstant;
import com.cap.bts.framework.sms.dto.SMSTextMessage;

/**
 * @author YIFEGU
 *
 */
public class HttpSMSProcessUtil {
    
    private static Logger logger = Logger.getLogger(HttpSMSProcessUtil.class);
    
    public static String sendMessage(SMSTextMessage textMessage){
    	String result = "";
        URL u = null;
        HttpURLConnection con = null;
        InputStream inputStream = null;
        ByteArrayOutputStream baos = null;
        String username = HttpSMSPropertiesUtil.getProperties(HttpSMSConstant.HTTP_SMS_USERNAME);
        String password = HttpSMSPropertiesUtil.getProperties(HttpSMSConstant.HTTP_SMS_PASSWORD);
        String url = HttpSMSPropertiesUtil.getProperties(HttpSMSConstant.HTTP_SMS_URL);
        String encoding = HttpSMSPropertiesUtil.getProperties(HttpSMSConstant.HTTP_SMS_ENCODING);
        
        //尝试发送请求
        try {
            url = url+"?username="+username+"&password="+password+"&mobile="+textMessage.getMobile()+
            "&message="+URLEncoder.encode(textMessage.getContent(), encoding);
            
            /*String url = "http://211.151.85.133:8080/sendsms.asp?username=tyreplus&password=888888&mobile="+textMessage.getMobile()+
            "&message="+textMessage.getContent();*/
            u = new URL(url);
            con = (HttpURLConnection) u.openConnection();
            // https 的用户名密码验证
            /*if (username != null && password != null) {
                Base64Encoder encoder = new Base64Encoder();
                String author = encoder.encode((username + ":" + password)
                        .getBytes());
                con.setRequestProperty("Authorization", "Basic "
                        + author);
            }*/
            
            con.setRequestMethod("GET");
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setUseCaches(false);
            //con.setInstanceFollowRedirects(true);  
            //con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");   
            
            //con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");    
           
            con.connect();  
            //add
            
            // 获取服务器响应代码
            int responsecode = con.getResponseCode();
            //读取返回内容
            if(200 == responsecode){
                try {
                    //读取返回内容
                    inputStream = con.getInputStream();
                    baos = new ByteArrayOutputStream();
                    int i = -1;
                    while ((i = inputStream.read()) != -1) {
                        baos.write(i);
                    }
                    result = baos.toString();
                    
                } catch (Exception e) {
                    logger.error("sendMessage",e);
                    result = "-error";
                }finally{
                    if(inputStream != null){
                        inputStream.close();
                    }
                    if(baos != null){
                        baos.close();
                    }
                }
            }
        } catch (Exception e) {
            logger.error("sendMessage",e);
        } finally {
            if (con != null) {
                con.disconnect();
            }
            
        }
        return result;
    }
    
    public static boolean sendMessageOld(SMSTextMessage textMessage){
        boolean result = true;
        URL u = null;
        HttpURLConnection con = null;
        InputStream inputStream = null;
        ByteArrayOutputStream baos = null;
        String username = HttpSMSPropertiesUtil.getProperties(HttpSMSConstant.HTTP_SMS_USERNAME);
        String password = HttpSMSPropertiesUtil.getProperties(HttpSMSConstant.HTTP_SMS_PASSWORD);
        String url = HttpSMSPropertiesUtil.getProperties(HttpSMSConstant.HTTP_SMS_URL);
        
        //尝试发送请求
        try {
            url = url+"?username="+username+"&password="+password+"&mobile="+textMessage.getMobile()+
            "&message="+URLEncoder.encode(textMessage.getContent(),"GBK");
            
            /*String url = "http://211.151.85.133:8080/sendsms.asp?username=tyreplus&password=888888&mobile="+textMessage.getMobile()+
            "&message="+textMessage.getContent();*/
            u = new URL(url);
            con = (HttpURLConnection) u.openConnection();
            // https 的用户名密码验证
            /*if (username != null && password != null) {
                Base64Encoder encoder = new Base64Encoder();
                String author = encoder.encode((username + ":" + password)
                        .getBytes());
                con.setRequestProperty("Authorization", "Basic "
                        + author);
            }*/
            
            con.setRequestMethod("GET");
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setUseCaches(false);
            //con.setInstanceFollowRedirects(true);  
            //con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");   
            
            //con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");    
           
            con.connect();  
            //add
            
            // 获取服务器响应代码
            int responsecode = con.getResponseCode();
            //读取返回内容
            if(200 == responsecode){
                try {
                    //读取返回内容
                    inputStream = con.getInputStream();
                    baos = new ByteArrayOutputStream();
                    int i = -1;
                    while ((i = inputStream.read()) != -1) {
                        baos.write(i);
                    }
                    System.out.println(baos.toString());
                    if(baos == null || baos.toString().equals("-15")){
                        result = false;
                    }
                } catch (Exception e) {
                    logger.error("sendMessage",e);
                    result = false;
                }finally{
                    if(inputStream != null){
                        inputStream.close();
                    }
                    if(baos != null){
                        baos.close();
                    }
                }
            }
        } catch (Exception e) {
            logger.error("sendMessage",e);
        } finally {
            if (con != null) {
                con.disconnect();
            }
            
        }
        return result;
    }
    
    
    
    public static List<SmsStatus> loadStatus(){
    	List<SmsStatus> list = new ArrayList<SmsStatus>();
        URL u = null;
        HttpURLConnection con = null;
        InputStream inputStream = null;
        ByteArrayOutputStream baos = null;
        String username = HttpSMSPropertiesUtil.getProperties(HttpSMSConstant.HTTP_SMS_USERNAME);
        String password = HttpSMSPropertiesUtil.getProperties(HttpSMSConstant.HTTP_SMS_PASSWORD);
        String statusUrl = HttpSMSPropertiesUtil.getProperties(HttpSMSConstant.HTTP_SMS_STATUS_URL);
        
        //尝试发送请求
        try {
        	statusUrl = statusUrl+"?username="+username+"&password="+password;
            
            u = new URL(statusUrl);
            con = (HttpURLConnection) u.openConnection();
            // https 的用户名密码验证
            /*if (username != null && password != null) {
                Base64Encoder encoder = new Base64Encoder();
                String author = encoder.encode((username + ":" + password)
                        .getBytes());
                con.setRequestProperty("Authorization", "Basic "
                        + author);
            }*/
            
            con.setRequestMethod("GET");
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setUseCaches(false);
            con.setConnectTimeout(30000);
            con.setReadTimeout(30000);
            //con.setInstanceFollowRedirects(true);  
            //con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");   
            
            //con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");    
           
            con.connect();  
            //add
            
            // 获取服务器响应代码
            int responsecode = con.getResponseCode();
            //读取返回内容
            if(200 == responsecode){
                try {
                    //读取返回内容
                    inputStream = con.getInputStream();
                    baos = new ByteArrayOutputStream();
                    int i = -1;
                    while ((i = inputStream.read()) != -1) {
                        baos.write(i);
                    }
                    String result = baos.toString();
                    
                    list = buildSmsStatusFromXml(result);
                    
                    
                } catch (Exception e) {
                    logger.error("get SMS status error",e);
                }finally{
                    if(inputStream != null){
                        inputStream.close();
                    }
                    if(baos != null){
                        baos.close();
                    }
                }
            }
        } catch (Exception e) {
            logger.error("sendMessage",e);
        } finally {
            if (con != null) {
                con.disconnect();
            }
            
        }
        return list;
    }
    
    
    /*
     * 
     * <?xml version="1.0" encoding="UTF-8" ?>
<Response>
<Report>
<MsgID>290684264</MsgID>
<Mobile>15052072870</Mobile>
<Status>DELIVRD</Status>
</Report>
     * 
     * */
    
    private static List<SmsStatus> buildSmsStatusFromXml(String xmlText) throws DocumentException{
    	List<SmsStatus> list = new ArrayList<SmsStatus>();
    	
    	xmlText = StringUtils.trim(xmlText);
    	if(StringUtils.isBlank(xmlText)){
    		return list;
    	}
		
		Document document = DocumentHelper.parseText(xmlText);
		Element rootElement = document.getRootElement();
		
		
		List<Node> reportNodes = rootElement.selectNodes("Report");
		if(reportNodes != null && !reportNodes.isEmpty()){
			for(Node node : reportNodes){
				SmsStatus smsStatus = new SmsStatus();
				
				smsStatus.setMsgId(getNodeValue(node, "MsgID"));
				smsStatus.setMobile(getNodeValue(node, "Mobile"));
				smsStatus.setStatus(getNodeValue(node, "Status"));
				
				list.add(smsStatus);
			}
		}
		
		return list;
	}
    
    
    private static String getNodeValue(Node rootElement, String select){
		Node node = rootElement.selectSingleNode(select);
		if(node != null){
			return node.getText();
		}
		
		return null;
	}


    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        SMSTextMessage message = new SMSTextMessage();
        message.setContent("【驰加汽车服务中心】亲爱的驰加会员，即日起至9月底，可到就近驰加店购买轮胎 优惠8折，敬请光临");
//        message.setMobile("18013260519");
        message.setMobile("15201886226");
        System.out.println("#########"+sendMessage(message));
        String xml = 
    			"<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" +
    			"<Response>\n" +
    			"<Report>\n" +
    			"<MsgID>290684264</MsgID>\n" +
    			"<Mobile>15052072870</Mobile>\n" +
    			"<Status>DELIVRD</Status>\n" +
    			"</Report>\n" +
    			"<Report>\n" +
    			"<MsgID>290690908</MsgID>\n" +
    			"<Mobile>13984437789</Mobile>\n" +
    			"<Status>DELIVRD</Status>\n" +
    			"</Report>\n" +
    			"<Report>\n" +
    			"</Response>\n";
        
        try {
//			List<SmsStatus> list =  buildSmsStatusFromXml(xml);
//			List<SmsStatus> list =  loadStatus();
//			System.out.println(list.size());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

    }

}
